package com.feinno.urcs.group.http.task;

import com.feinno.sip.address.SipUri;
import com.feinno.sip.header.CSeq;
import com.feinno.sip.header.CallID;
import com.feinno.sip.message.SipRequest;
import com.feinno.urcs.group.pd.task.entity.PdBaseGroupNotifyArgs;
import com.feinno.urcs.nai.IMPU;
import com.feinno.urcs.sip.SipConnector;
import com.feinno.urcs.sip.UrcsSipFactory;
import com.feinno.urcs.sipservlet.SipConnectorLoader;
import com.feinno.urcs.sipservlet.SipServletRequest;
import com.feinno.urcs.sipservlet.SipServletRequestFactory;
import com.feinno.urcs.sipservlet.message.SipMessageBuilder;
import org.helium.framework.annotations.FieldSetter;

import javax.sip.InvalidArgumentException;
import javax.sip.address.Address;
import javax.sip.address.URI;
import javax.sip.message.Request;
import java.text.ParseException;

/**
 * Created by wuzhiguo on 15-6-5.
 */
public class PdBaseNotifyTask {

	@FieldSetter(loader = SipConnectorLoader.class, value = "${SIP_STACK_AS}")
	private SipConnector connector;
	protected String cscfHost;

	protected SipServletRequest createSipRequest(PdBaseGroupNotifyArgs baseGroupNotify, byte[] content) throws ParseException, InvalidArgumentException {
		SipUri fromUri = (SipUri) IMPU.parse(baseGroupNotify.getFromUri()).toUri();
		URI toUri = IMPU.parse(baseGroupNotify.getToUri()).toUri();
		Address fromAddress = UrcsSipFactory.getAddressFactory().createAddress(fromUri);
		Address toAddress = UrcsSipFactory.getAddressFactory().createAddress(toUri);
		SipRequest sipRequest = UrcsSipFactory.getMessageFactory().createRequest(connector.getSipProvider(), Request.NOTIFY, toAddress, fromAddress);
		SipServletRequest sipServletRequest = new SipMessageBuilder(SipServletRequestFactory.createRequest(sipRequest, connector))
				.requestUri(UrcsSipFactory.getAddressFactory().createURI(baseGroupNotify.getRequestUri()))
				.fromTag(baseGroupNotify.getFromTag())
				.toTag(baseGroupNotify.getToTag())
				.removeHeader(CallID.NAME)
				.callId(baseGroupNotify.getCallId())
				.removeHeader(CSeq.NAME)
				.cSeq(baseGroupNotify.getCseq(), Request.NOTIFY)
				.pai(fromUri)
				.contact(fromUri.getUser(), fromUri.getHost(), "urn%3Aurn-7%3A3gpp-service.ims.icsi.oma.cpm.pagemode;urn%3Aurn-7%3A3gppservice.ims.icsi.oma.cpm.filetransfer", true)
				.maxForwards(70)
				.supported("timer")
				.subscriptionState(baseGroupNotify.getExpired())
				.event("xcap-diff")
				.content(content, "application", "xcap-diff+xml")
				.route(cscfHost)
				.toSipServletReqeust();
		return sipServletRequest;
	}
}
